<template>
  <!-- 导入表 -->
  <el-dialog title="导入表" :visible.sync="visible" :width="dialogWidth" top="5vh" append-to-body>
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="数据源" prop="datasource">
        <el-select v-model="queryParams.datasource" placeholder="请选择数据源" clearable filterable remote size="small" @change="searchFieldChanged('datasource', $event)" :style="{width: '100%'}">
          <el-option v-for="(item, index) in datasourceOptions" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="数据库" prop="tableSchema">
        <el-select v-model="queryParams.tableSchema" placeholder="请选择数据库" clearable filterable remote size="small" @change="searchFieldChanged('tableSchema', $event)" :style="{width: '100%'}">
          <el-option v-for="(item, index) in tableSchemaOptions" :key="index" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="表名称" prop="tableName">
        <el-select v-model="queryParams.tableName" placeholder="请选择表名" clearable filterable allow-create remote size="small" @change="searchFieldChanged('tableName', $event)" :style="{width: '100%'}">
          <el-option v-for="(item, index) in tableNameOptions" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="表描述" prop="tableComment">
        <el-select v-model="queryParams.tableComment" placeholder="请选择表描述" clearable filterable allow-create remote size="small" @change="searchFieldChanged('tableComment', $event)" :style="{width: '100%'}">
          <el-option v-for="(item, index) in tableCommentOptions" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row>
      <el-form :model="queryParams" ref="importParams" :inline="true">
        <el-form-item label="应用" prop="applicationId">
          <el-select v-model="queryParams.applicationId" placeholder="请选择应用" clearable size="small" @change="importParamsChanged('applicationId', $event)" :style="{width: '100%'}">
            <el-option v-for="(item, index) in applicationIdOptions" :key="item.key" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模块" prop="moduleId">
          <el-select v-model="queryParams.moduleId" placeholder="请选择模块" clearable size="small" @change="importParamsChanged('moduleId', $event)" :style="{width: '100%'}">
            <el-option v-for="(item, index) in moduleIdOptions" :key="item.key" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-table @row-click="clickRow" ref="table" :data="dbTableList" @selection-change="handleSelectionChange" height="260px">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="tableName" label="表名称" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="tableComment" label="表描述" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column prop="updateTime" label="更新时间"></el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleImportTable">确 定</el-button>
      <el-button @click="visible = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { dbSearchInit, dbSearchChanged, listDbSchema, listDbTable } from "@/api/tool/gen/dbinfo";
  import { importParamsChanged, importTable } from "@/api/tool/gen/table";
  export default {
    data() {
      return {
        // 对话框的宽度
        dialogWidth: "100%",
        // 遮罩层
        visible: false,
        // 应用选项
        applicationIdOptions: undefined,
        // 模块选项
        moduleIdOptions: undefined,
        // 待选数据源
        datasourceOptions: undefined,
        // 待选数据库
        tableSchemaOptions: undefined,
        // 待选表名
        tableNameOptions: undefined,
        // 待选表说明
        tableCommentOptions: undefined,
        // 选中数组值
        tables: [],
        // 总条数
        total: 0,
        // 表数据
        dbTableList: [],
        // 查询参数
        queryParams: {
          datasource: 'Primary',
          tableSchema: undefined,
          applicationId: undefined,
          moduleId:  undefined,
          tableName: undefined,
          tableComment: undefined,
          params: {}
        }
      };
    },
    mounted(){
      // 在组件挂载后设置对话框宽度为视口宽度的 80%
      this.dialogWidth = ""+(window.innerWidth>=800?800:window.innerWidth);
    },
    watch: {
      // 监听窗口大小变化，动态调整对话框宽度
      window: {
        immediate: true,
        handler(newValue, oldValue) {
          console.log("调试：this.dialogWidth="+this.dialogWidth, "newValue="+newValue, "oldValue"+oldValue);
          this.dialogWidth = ""+(newValue>=800?800:newValue); // 调整为你需要的比例
        },
      },
    },
    methods: {
      // 打开弹窗
      open() {
        // 搜索字段初始化
        this.searchFieldInit();
        // 导入参数初始化
        this.importParamsChanged();
      },
      // 搜索字段初始化
      searchFieldInit() {
        dbSearchInit(this.queryParams).then(res => {
          this.datasourceOptions = res.data.params.datasourceOptions;
          if(res.data.params.tableSchemaOptions){
            this.tableSchemaOptions = res.data.params.tableSchemaOptions;
          }else{
            this.tableSchemaOptions = [];
          }
          if(res.data.params.tableNameOptions){
            this.tableNameOptions = res.data.params.tableNameOptions;
          }else{
            this.tableNameOptions = [];
          }
          if(res.data.params.tableCommentOptions){
            this.tableCommentOptions = res.data.params.tableCommentOptions;
          }else{
            this.tableCommentOptions = [];
          }
          this.queryParams.tableComment = res.data.tableComment;
          this.visible = true;
        });
      },
      // 数据源选择改变
      searchFieldChanged(changedField, value) {
        console.log(changedField, value);
        this.queryParams.params['changedField'] = changedField;
        dbSearchChanged(this.queryParams).then(res => {
          if(res.data.params.datasourceOptions){
            this.datasourceOptions = res.data.params.datasourceOptions;
          }
          if(res.data.params.tableSchemaOptions){
            this.tableSchemaOptions = res.data.params.tableSchemaOptions;
          }else{
            this.tableSchemaOptions = [];
          }
          if(res.data.params.tableNameOptions){
            this.tableNameOptions = res.data.params.tableNameOptions;
          }else{
            this.tableNameOptions = [];
          }
          if(res.data.params.tableCommentOptions){
            this.tableCommentOptions = res.data.params.tableCommentOptions;
          }else{
            this.tableCommentOptions = [];
          }
          this.queryParams.tableComment = res.data.tableComment;
          this.visible = true;
        });
      },
      // 导入参数初始化
      importParamsInit() {
        delete this.queryParams.params['changedField'];
        importParamsChanged(this.queryParams).then(res => {
          this.queryParams = res.data;
        //   if(res.data.params.importParamsColumns){
        //     this.applicationIdOptions = res.data.params.importParamsColumns.applicationId.selectOptions;
        //     this.moduleIdOptions      = res.data.params.importParamsColumns.moduleId.selectOptions;
        //   }
        });
      },
      // 导入参数选择改变
      importParamsChanged(changedField, value) {
        this.queryParams.params['changedField'] = changedField;
        importParamsChanged(this.queryParams).then(res => {
          if(res.data.params.importParamsColumns){
            this.applicationIdOptions = res.data.params.importParamsColumns.applicationId.selectOptions;
            this.moduleIdOptions      = res.data.params.importParamsColumns.moduleId.selectOptions;
          }
        });
      },
      clickRow(row) {
        this.$refs.table.toggleRowSelection(row);
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.tables = selection.map(item => item.tableName);
      },
      // 查询表数据
      getList() {
        listDbTable(this.queryParams).then(res => {
          if (res.code === 200) {
            this.dbTableList = res.rows;
            this.total = res.total;
          }
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 导入按钮操作 */
      handleImportTable() {
        const tableNames = this.tables.join(",");
        if (tableNames == "") {
          this.$modal.msgError("请选择要导入的表");
          return;
        }
        importTable({
          datasource: this.queryParams.datasource,
          tableSchema: this.queryParams.tableSchema,
          tables: tableNames,
          applicationId: this.queryParams.applicationId ,
          moduleId: this.queryParams.moduleId
        }).then(res => {
          this.$modal.msgSuccess(res.msg);
          if (res.code === 200) {
            this.visible = false;
            this.$emit("ok");
          }
        });
      }
    }
  };
</script>
